<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
import { formatExcelDate } from '@/utils'
import { importEmployee } from '@/api/employee'
export default {
  methods: {
    async handleSuccess({ header, results }) {
      try {
        // console.log(header, results)
        const newData = this.transExcel(results, header)
        console.log('转换之后的数据', newData)

        // 调用接口
        await importEmployee(newData)
        // 提示
        this.$message.success('导入成功')
        // 回到列表页
        this.$router.push('/employees')
      } catch (err) {
        this.$message.error(err)
      }
    },
    transExcel(results, header) {
      console.log('转换之前的数据', results, header)
      // 拿到中文的key
      const zhKeys = Object.keys(results[0])
      // console.log(zhKeys)
      const mapInfo = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
        聘用形式: 'formOfEmployment'
      }
      return results.map((item) => {
        const obj = {}
        zhKeys.forEach((zhkey) => {
          // 拿到英文的key
          const enKeys = mapInfo[zhkey]
          // 日期时间要转换为标准时间
          if (enKeys === 'timeOfEntry' || enKeys === 'correctionTime') {
            obj[enKeys] = new Date(formatExcelDate(item[zhkey]))
          } else {
            obj[enKeys] = item[zhkey]
          }
        })
        return obj
      })
    }
  }
}
</script>
